
#include <iostream>
#include "mqtt.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include "link.h"

using namespace std;

int parse_type(unsigned char tt)
{


      return tt&0xf0;


}

void mqtt_connect(int fd,const char*buffer)
 {

   //printf("剩余长度 %d\n",buffer[1]);
   // printf("协议名称 %s\n",&buffer[4]); 
   unsigned char back[64]={0};

   back[0]=CONNACK;
   back[1]=0x02;
   back[2]=0x00;
   back[3]=0x00;

  if(send(fd,back,4,0)<0)
  {
        cout<<"connack fail..."<<endl;
  }

 }


  void mqtt_subscribe(int fd,const char*buffer)
  {

//    for(int i=0;i<11;i++)
//    {
//     printf("%x ",buffer[i]);
//    }
//    printf("\n");
      printf("[SUBSCRIBE]");
      char MSB=buffer[2];
      char LSB=buffer[3];
      char back[32]={0};
      short topiclen=buffer[5];
      
      memcpy(back,&buffer[6],topiclen);

      printf("主题长度为：%d 主题为%s\n",topiclen,back);

       unsigned char ret[64]={0};
    
      ret[0]=SUBACK;
      ret[1]=0x03;
      ret[2]=MSB;
      ret[3]=LSB;
      ret[4]=0x00;
      if(send(fd,ret,5,0)<0)
  {
        cout<<"suback fail..."<<endl;
  }


     add_link(fd,back);

  //当有客户端订阅的话，就把该订阅放入链表中，等到发布去该链表中去找
     
  }


  void   mqtt_publish(int fd,const char*buffer)
  {

//    for(int i=0;i<20;i++)
//    {

//     printf("%x ",buffer[i]);
//    }
//     printf("\n");

      printf("[PUBLISH]");
      int remain=buffer[1];
      int topiclen=((short)buffer[2]<<8)+buffer[3];
      char msg[64]={0};
      char topic[32]={0};
      memcpy(topic,&buffer[4],topiclen);
      memcpy(msg,&buffer[8],remain-topiclen);
      printf("主题名 %s 内容为：%s\n",topic,msg);
      
      real_publish(topic,msg,remain-topiclen);

  }

  void notify(int fd,const char*topic,const char*msg,int msglen)
  {
      char buffer[512]={0};
      int index=0;
      int topiclen=strlen(topic);
      buffer[index++]=PUBLISH;
      buffer[index++]=2+topiclen+msglen+1;
      buffer[index++]=0;
      buffer[index++]=topiclen;
      memcpy(&buffer[index],topic,topiclen);
      index+=topiclen;
      memcpy(&buffer[index],msg,msglen);
      index+=msglen;
      buffer[index]=0x00;


      if(send(fd,buffer,5+topiclen+msglen,0)<0)
      {
         cout<<"send fail..."<<endl;


      }
     

  }
